import express from 'express'
import dotenv from 'dotenv'
import type { RequestProps } from './types'
import type { ChatMessage } from './chatgpt'
import { chatConfig, chatReplyProcess, currentModel } from './chatgpt'
import { auth } from './middleware/auth'
import { limiter } from './middleware/limiter'
import { isNotEmptyString } from './utils/is'

const app = express()
const router = express.Router()

app.use(express.static('public'))
app.use(express.json())

// 注入环境变量node环境配置全局变量
dotenv.config()

// node环境配置全局变量
dotenv.config()

app.all('*', (_, res, next) => {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'authorization, Content-Type')
  res.header('Access-Control-Allow-Methods', '*')
  next()
})

router.post('/chat-process', [auth, limiter], async (req, res) => {
  res.setHeader('Content-type', 'application/octet-stream')

  try {
    const { prompt, options = {}, systemMessage, temperature, top_p } = req.body as RequestProps
    let firstChunk = true

    // let resData = {
    //   role: "assistant",
    //   id: "chatcmpl-1703495659305046528",
    //   parentMessageId: "0001a02f-dc41-46b3-a35e-2a9e911850ef",
    //   text: "你好呀，很高兴能为你提供服务。有什么我可以帮助你的吗？",
    //   delta: "",
    //   detail: {
    //     id: "chatcmpl-1703495659305046528",
    //     object: "chat.completions.chunk",
    //     created: 1703495659,
    //     model: "cl-34b-v2.gguf",
    //     choices: [
    //       {
    //         index: 0,
    //         finish_reason: null,
    //         message: {
    //           role: "assistant",
    //           content: "",
    //         },
    //         delta: {
    //           role: "assistant",
    //           content: "",
    //         },
    //       },
    //     ],
    //     usage: {
    //       prompt_tokens: 70,
    //       completion_tokens: 35,
    //       total_tokens: 105,
    //     },
    //   },
    // }

    // // let resData = await mockDatas() 
    // res.write(firstChunk ? JSON.stringify(resData) : `\n${JSON.stringify(resData)}`)
    // firstChunk = false

    await chatReplyProcess({
      message: prompt,
      lastContext: options,
      process: (chat: ChatMessage) => {
        res.write(firstChunk ? JSON.stringify(chat) : `\n${JSON.stringify(chat)}`)
        firstChunk = false
      },
      systemMessage,
      temperature,
      top_p,
    })
  }
  catch (error) {
    res.write(JSON.stringify(error))
  }
  finally {
    res.end()
  }
})

router.post('/config', auth, async (req, res) => {
  try {
    const response = await chatConfig()
    res.send(response)
  }
  catch (error) {
    res.send(error)
  }
})

router.post('/session', async (req, res) => {
  try {
    const AUTH_SECRET_KEY = process.env.AUTH_SECRET_KEY
    const hasAuth = isNotEmptyString(AUTH_SECRET_KEY)
    res.send({ status: 'Success', message: '', data: { auth: hasAuth, model: currentModel() } })
  }
  catch (error) {
    res.send({ status: 'Fail', message: error.message, data: null })
  }
})

router.post('/verify', async (req, res) => {
  try {
    const { token } = req.body as { token: string }
    if (!token)
      throw new Error('Secret key is empty')

    if (process.env.AUTH_SECRET_KEY !== token)
      throw new Error('密钥无效 | Secret key is invalid')

    res.send({ status: 'Success', message: 'Verify successfully', data: null })
  }
  catch (error) {
    res.send({ status: 'Fail', message: error.message, data: null })
  }
})

app.use('', router)
app.use('/api', router)
app.set('trust proxy', 1)

app.listen(3002, () => globalThis.console.log('Server is running on port 3002'))
